from django_filters.rest_framework import FilterSet
from django_filters.filters import *
from .models import *


class JobFilterSet(FilterSet):
    name = CharFilter(lookup_expr="contains")
    start_time = DateFilter(
        field_name="create_time", lookup_expr="gte", label="开始日期"
    )
    end_time = DateFilter(field_name="create_time", lookup_expr="lt", label="结束日期")

    class Meta:
        model = Job
        fields = [
            "name",
            "product",
            "type",
            "policy",
            "env",
            "level",
            "testplan",
            "owner",
            "creator",
            "status",
            "start_time",
            "end_time",
        ]


class JobExecutionFilterSet(FilterSet):
    name = CharFilter(lookup_expr="contains")
    start_time = DateFilter(
        field_name="create_time", lookup_expr="gte", label="开始日期"
    )
    end_time = DateFilter(field_name="create_time", lookup_expr="lt", label="结束日期")

    class Meta:
        model = JobExecution
        fields = [
            "job",
            "status",
            "start_time",
            "end_time",
        ]


class JobLogFilterSet(FilterSet):
    name = CharFilter(lookup_expr="contains")
    start_time = DateFilter(
        field_name="create_time", lookup_expr="gte", label="开始日期"
    )
    end_time = DateFilter(field_name="create_time", lookup_expr="lt", label="结束日期")
    module_name = CharFilter(field_name="module", method="search_by_module_name")

    def search_by_module_name(self, queryset, field, value):
        return queryset.filter(module__name__icontains=value)

    class Meta:
        model = JobLog
        fields = [
            "job",
            "job_execution",
            "testcase",
            "number",
            "name",
            "type",
            "analysis",
            "status",
            "start_time",
            "end_time",
            "module_name",
        ]
